<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="特权名称" prop="superName">
            <el-input
              v-model="queryParams.superName"
              placeholder="请输入特权名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="特权周期" prop="cycle">
            <el-input
              v-model="queryParams.cycle"
              placeholder="请输入特权周期"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建日期" prop="createdate">
            <el-date-picker
              clearable
              size="small"
              style="width: 190px"
              v-model="queryParams.createdate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择创建日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          type="primary"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" size="mini" @click="handleCopy"
          >协议</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
         plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['customer:super:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      stripe
      v-loading="loading"
      :data="superList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <!--      <el-table-column label="创建日期" align="left" prop="superId" />-->
      <el-table-column label="特权名称" align="left">
        <template slot-scope="{ row }">
          {{ row.showName ? row.showName : row.superName }}
        </template>
      </el-table-column>
      <el-table-column label="特权周期" align="left" prop="cycle" />
      <el-table-column label="售价" align="left" prop="price" />
      <el-table-column label="原价" align="left" prop="originalPrice" />
      <el-table-column label="积分倍数" align="left" prop="multiple" />
      <el-table-column label="立减活动" align="left" prop="activityName" />
      <el-table-column label="优惠券活动" align="left" prop="couponIssueName" />
      <el-table-column label="是否启用" width="80px" align="left">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value="0"
            :inactive-value="1"
            @change="updateEnable(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建日期"
        align="left"
        prop="createdate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:super:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customer:super:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-sugar"
            @click="handleAddUser(scope.row)"
            >添加会员</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【超级会员】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="82px">
        <el-form-item
          label="特权名称"
          prop="superName"
          class="item-radio-button"
        >
          <!-- <el-input v-model="form.superName" placeholder="请输入特权名称" /> -->
          <el-radio-group
            v-model="form.superName"
            size="medium"
            @input="inputRadioSuperName"
          >
            <el-radio-button
              label="月卡"
              class="radio-button"
            ></el-radio-button>
            <el-radio-button
              label="季卡"
              class="radio-button"
            ></el-radio-button>
            <el-radio-button
              label="年卡"
              class="radio-button"
            ></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="showName">
          <el-input
            type="text"
            v-model="form.showName"
            placeholder="请输入名称"
            maxlength="15"
            @input="updateSuperName"
          ></el-input>
        </el-form-item>
        <el-form-item label="特权周期" prop="cycle">
          <el-input
            type="text"
            v-model="form.cycle"
            placeholder="请输入特权周期"
            maxlength="11"
            onkeyup="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input
            v-model="form.price"
            placeholder="请输入售价"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input
            v-model="form.originalPrice"
            placeholder="请输入原价"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="积分倍数" prop="multiple">
          <el-input
            style="width: 370px"
            v-model="form.multiple"
            placeholder="请输入积分倍数"
            type="text"
            maxlength="11"
            onkeyup="value=value.replace(/[^\d]/g,'')"
          />
        </el-form-item>
        <el-form-item label="赠送优惠券">
          <el-select
            style="width: 370px"
            v-model="form.couponIssueIds"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in MemberCreationList"
              :key="item.id"
              :label="item.issueRemark"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="立减活动" prop="activityId">
          <el-select
            v-model="form.activityId"
            style="width: 200px; font-size: 10px"
          >
            <el-option
              v-for="item in reductionActivityList"
              :key="item.activityId"
              :label="item.activityName"
              :value="item.activityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券活动" prop="couponIssueId">
          <el-select
            v-model="form.couponIssueId"
            style="width: 200px; font-size: 10px"
          >
            <el-option
              v-for="item in couponIssueList"
              :key="item.id"
              :label="item.issueName"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="0启用，1停用" prop="enable">
          <el-input v-model="form.enable" placeholder="请输入0启用，1停用" />
        </el-form-item> -->
        <el-form-item label="会员权益" prop="superUserTerm">
          <el-input
            type="textarea"
            :rows="2"
            class="textarea_style"
            v-model="form.superUserTerm"
            placeholder="请输入会员权益"
            maxlength="500"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="submitForm" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加会员 -->
    <el-dialog
      :title="title"
      :visible.sync="openPhone"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-form-item label="会员手机号" prop="phone">
          <el-input
            v-model="form.phone"
            :autosize="{ minRows: 25, maxRows: 400 }"
            placeholder="请输入会员手机号,回车换行即可"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="funUserAdd">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置会员权益文案 -->
    <el-drawer
      title="超级会员设置"
      :visible.sync="settingDrawer"
      :before-close="handleClose"
    >
      <el-form ref="settingForm" :model="settingForm" class="settingForm">
        <el-form-item>
          <div><span>请输入《超级会员服务协议》</span></div>
          <el-input
            v-model="settingForm.superUserAgreement"
            style="width: 80%"
            type="textarea"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <div><span>请输入预热界面超级会员介绍文案</span></div>
          <el-input
            v-model="settingForm.preheatCopy"
            style="width: 80%"
            type="textarea"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button type="primary" @click="submitCopy">确认</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listSuper,
  getSuper,
  delSuper,
  addSuper,
  updateSuper,
  exportSuper,
  addSuperPhone,
  saveCopy,
  getCopy,
} from "@/api/station/super";
import { listReductionActivity } from "@/api/market/reductionActivity";
import { listIssue4Relation, creationList } from "@/api/coupon";
export default {
  name: "Super",
  data() {
    // 销售价格
    let checkPrice = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{1,2})?$/;
      if (!value) return callback(new Error("请输入金额"));
      if (String(value).startsWith("."))
        return callback(new Error("请输入有效数值"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("金额最多保留两位小数"));
      callback();
    };
    return {
      settingDrawer: false, // 设置文案弹窗
      settingForm: {}, //设置文案表单
      // 会员优惠券列表
      MemberCreationList: [],
      value1: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【超级会员】表格数据
      superList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openPhone: false,
      // 立减活动表格数据
      reductionActivityList: [],
      // 发布过的优惠券活动
      couponIssueList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        superName: null,
        cycle: null,
        price: null,
        originalPrice: null,
        multiple: null,
        activityId: null,
        couponIssueId: null,
        enable: null,
        createdate: null,
      },
      // 查询参数
      queryActivityParams: {
        memberTags: "super",
        pageNum: 1,
        pageSize: 100,
      },
      queryCouponIssueParams: {
        pageNum: 1,
        pageSize: 100,
      },
      // 表单参数
      form: {
        superUserTerm: "详询油站工作人员",
        showName: "月卡",
        couponIssueIds: [],
      },
      rules: {
        showName: [
          { required: true, message: "请输入名称", trigger: "change" },
        ],
        superName: [
          { required: true, message: "请输入特权名称", trigger: "blur" },
        ],
        cycle: [
          {
            required: true,
            message: "请输入特权周期以天为单位",
            trigger: "blur",
          },
          {
            pattern: /^\d{1,11}$/,
            message: "长度在 1 到 11个数字",
            trigger: "blur",
          },
        ],
        price: [{ required: true, validator: checkPrice, trigger: "change" }],
        originalPrice: [
          { required: true, validator: checkPrice, trigger: "change" },
        ],
        multiple: [
          { required: true, message: "请输入积分倍数", trigger: "blur" },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "请输入合法整数或者小数",
            trigger: "blur",
          },
        ],
        activityId: [
          { required: true, message: "请选择规则分组", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.initData();
  },
  methods: {
    // 打开协议
    handleCopy() {
      this.getCopyInfo().then(() => {
        this.settingDrawer = true;
      });
    },
    // 特权名称和名称 联动
    updateSuperName() {
      if (this.form.showName === "月卡") {
        this.form.superName = "月卡";
      } else if (this.form.showName == "季卡") {
        this.form.superName = "季卡";
      } else if (this.form.showName == "年卡") {
        this.form.superName = "年卡";
      }
    },
    //  修改预热文案和协议
    async submitCopy() {
      await saveCopy(this.settingForm);
      this.$message.success("保存成功");
    },
    // 获取预热文案和协议
    async getCopyInfo() {
      const res = await getCopy();
      this.$set(this.settingForm, "preheatCopy", res.data.preheatCopy);
      this.$set(
        this.settingForm,
        "superUserAgreement",
        res.data.superUserAgreement
      );
    },
    // 处理弹窗关闭
    handleClose() {
      this.settingDrawer = false;
    },
    // 特权名称
    inputRadioSuperName() {
      // console.log("特权名称", this.form.superName);
    },
    /** 会员和手机号绑定 */
    handleAddUser(row) {
      this.form = row;
      this.form.superName = row.superName;
      const that = this;
      const curName = this.form.showName
        ? this.form.showName
        : this.form.superName;
      this.$confirm('是否确认"' + curName + '"绑定会员?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        that.openPhone = true;
      });
    },
    funUserAdd() {
      var data = this.form;
      if (data.enable == true) {
        data.enable = 1;
      } else {
        data.enable = 0;
      }
      addSuperPhone(data).then((response) => {
        if (response.code == 200) {
          this.msgSuccess("超级会员添加成功");
          this.opencancellation = false;
        } else {
          this.msgSuccess(response.msg);
        }
      });
    },
    /** 查询立减活动列表 */
    initData() {
      listReductionActivity(this.queryActivityParams).then((response) => {
        this.reductionActivityList = response.rows;
      });
      listIssue4Relation(this.queryCouponIssueParams).then((response) => {
        this.couponIssueList = response.rows;
      });
    },
    /** 查询【超级会员】列表 */
    getList() {
      this.loading = true;
      listSuper(this.queryParams).then((response) => {
        this.superList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openPhone = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        superId: null,
        superName: null,
        cycle: null,
        price: null,
        originalPrice: null,
        multiple: null,
        activityId: null,
        couponIssueId: null,
        enable: null,
        createdate: null,
        superUserTerm: "详询油站工作人员",
        showName: "月卡",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.superId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.creationList();
      this.title = "添加【超级会员】";
      this.$nextTick(() => {
        const aaa = document.getElementsByClassName(
          "el-form-item item-radio-button is-required"
        );
        aaa[0].children[1].style.marginLeft = "0px";
        this.form.superName = "月卡";
      });
    },

    // 点击新增获取会员优惠券
    creationList() {
      creationList({ status: 1 }).then((res) => {
        this.MemberCreationList = res.rows;
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.creationList();
      this.reset();
      const superId = row.superId || this.ids;
      getSuper(superId).then((response) => {
        this.form = response.data;
        if (response.data.couponIssueIds) {
          this.form.couponIssueIds = response.data.couponIssueIds.split(",");
        } else {
          this.form.couponIssueIds = [];
        }
        this.form.showName = response.data.showName
          ? response.data.showName
          : response.data.superName;
        this.open = true;
        this.title = "修改【超级会员】";
        this.$nextTick(() => {
          const aaa = document.getElementsByClassName(
            "el-form-item item-radio-button is-required"
          );
          aaa[0].children[1].style.marginLeft = "0px";
        });
      });
    },
    updateEnable(data) {
      this.form.superId = data.superId;
      updateSuper(data).then((response) => {
        this.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },

    // 监控售价值变化
    handlInput(val) {
      // value=value.replace(/[^0-9.]/g,'')
      // console.log(val, 333);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const couponIssueIds = this.form.couponIssueIds.join(",");
          if (this.form.superId != null) {
            updateSuper({
              ...this.form,
              couponIssueIds,
            }).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSuper({
              ...this.form,
              couponIssueIds,
            }).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const superIds = row.superId || this.ids;
      this.$confirm(
        '是否确认删除【超级会员】编号为"' + superIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delSuper(superIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有【超级会员】数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportSuper(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
<style scoped lang="scss">
.item-radio-button {
  display: flex;
  flex-direction: column;
}
::v-deep.el-radio-button {
  margin: 0 25px;
  .el-radio-button__inner {
    //修改按钮样式
    text-align: center;
    line-height: 30px;
    padding: 0px;
    width: 100px;
    height: 30px;
    color: #409eff;
    border: 1px solid #409eff !important;
    border-radius: 5px;
  }
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    // 修改按钮激活样式
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
  }
}
.footer {
  margin-top: 2rem;
  width: 80%;
  text-align: right;
}
::v-deep .el-drawer__body {
  padding-left: 1rem;
}
::v-deep .el-textarea__inner {
  height: 10rem;
}
.settingForm {
  ::v-deep .el-textarea__inner {
    height: 16rem;
  }
}
.textarea_style {
  ::v-deep .el-textarea__inner {
    height: 4rem;
  }
}
</style>
